//
//  RechargeAlert.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/3/5.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import Foundation
import Then
import SnapKit
import RxSwift
import RxCocoa

class RechargeAlert: UIView {
    
    var compelete:((Bool)->Void)?
    
    var paperId: Int!
    var price: Int = 0
    var total: Int = 0
    var presentController: UIViewController?
    
    private var result = false
    private var backgroundView: UIView!
    private var contentView: UIView!
    private var disposeBag = DisposeBag()
    
    ///循环引用，防止自动Release掉
    fileprivate var selfReference: RechargeAlert?
    
    init(paperId: Int,
         price: Int,
         presentController: UIViewController,
         compelete:((Bool)->Void)? = nil) {
        self.paperId = paperId
        self.price = price
        self.presentController = presentController
        self.compelete = compelete
        super.init(frame: CGRect.zero)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
}

// MARK:-
// MARK: UI
extension RechargeAlert {
    func show() {
        
        
        selfReference = self
        
        ///获取用户信息
        getAccountInfo()
    }
    
  
    /// 隐藏
    ///
    /// - Parameter result: 是否充值成功
    ///   - destroy: 是否销毁自身
    func hideView(_ result: Bool? = nil, destroy: Bool = true) {
        if result != nil {
            self.result = result!
        }
        
        UIView.animate(withDuration: 0.25, animations: {
            self.alpha = 0
            self.backgroundView.alpha = 0
        }) { (finished) in
            self.removeFromSuperview()
            if destroy {
                self.selfReference = nil
                self.compelete?(self.result)
            }
        }
    }
  
    
    private func getAccountInfo() {
        //获取用户信息
        startAnimating()
        shurenProvider.rx.request(.userInfo)
            .asObservable()
            .mapRespnseToObject(type:AccountModel.self)
            .subscribe(onNext: { (account) in
                AccountStorage.default.updateAccount(account)
            }, onError: { [weak self] (error) in
                showError(error)
                stopAnimating()
                self?.selfReference = nil
                self?.hideView(false)
            }, onCompleted: { [weak self] in
                stopAnimating()
                self?.loadUI()
            }).disposed(by: disposeBag)
    }
    
    private func loadUI() {
        total = AccountStorage.default.account.goldCoin ?? 0
        setup()
        
        let rv = UIApplication.shared.keyWindow! as UIWindow
        rv.addSubview(self)
        
        UIView.animate(withDuration: 0.25) {
            self.alpha = 1.0
            self.backgroundView.alpha = 0.5
        }
    }
    
    private func setup() {
        self.frame = UIScreen.main.bounds
        self.alpha = 0
        self.backgroundColor = UIColor.clear
        
        backgroundView = UIView().then { (view) in
            view.backgroundColor = UIColor.black
            view.alpha = 0
            
            self.addSubview(view)
            view.snp.makeConstraints({ (maker) in
                maker.edges.equalTo(UIEdgeInsetsMake(0, 0, 0, 0))
            })
        }
        
        contentView = UIView().then { (view) in
            view.layer.cornerRadius = 5.0
            view.clipsToBounds = true
            view.backgroundColor = UIColor.white
            
            self.addSubview(view)
            view.snp.makeConstraints({ (maker) in
                maker.center.equalToSuperview()
                maker.width.equalTo(235)
            })
        }
        
        let titleLabel = UILabel().then { (label) in
            label.font = UIFont.systemFont(ofSize: 12)
            label.textAlignment = .center
            let str = "确认支付\(self.price)"
            let attri = NSMutableAttributedString.init(string: str)
            let attch = NSTextAttachment.init()
            //表情图片
            attch.image = UIImage.init(named: "Coin_small")
            //设置图片大小
            attch.bounds = CGRect.init(x: 2, y: -2, width: 12, height: 12)
            //创建带有图片的富文本
            let attchStr = NSAttributedString.init(attachment: attch)
            //在文字后面添加图片
            attri.append(attchStr)
            attri.append(NSAttributedString.init(string: " 打开试卷？"))
            label.attributedText = attri
            
            contentView.addSubview(label)
            label.snp.makeConstraints({ (make) in
                make.centerX.equalToSuperview()
                make.top.equalTo(12)
            })
        }
        
        let suTitlebLabel = UILabel().then { (label) in
            label.font = UIFont.systemFont(ofSize: 12)
            label.textAlignment = .center
            let str = "当前余额：\(self.total)"
            let attri = NSMutableAttributedString.init(string: str)
            let attch = NSTextAttachment.init()
            //表情图片
            attch.image = UIImage.init(named: "Coin_small")
            //设置图片大小
            attch.bounds = CGRect.init(x: 2, y: -2, width: 12, height: 12)
            //创建带有图片的富文本
            let attchStr = NSAttributedString.init(attachment: attch)
            //在文字后面添加图片
            attri.append(attchStr)
            label.attributedText = attri
            
            contentView.addSubview(label)
            label.snp.makeConstraints({ (make) in
                make.centerX.equalToSuperview()
                make.top.equalTo(titleLabel.snp.bottom).offset(5)
            })
        }
        
        let rechargeBtn = UIButton.init(type: .custom).then { (btn) in
            btn.setTitle("去充值>", for: .normal)
            btn.setTitleColor(Config.default.themeColor, for: .normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
            
            contentView.addSubview(btn)
            btn.snp.makeConstraints({ (make) in
                make.centerX.equalToSuperview()
                make.top.equalTo(suTitlebLabel.snp.bottom).offset(5)
            })
        }
        
        //横线
        let lineView = UIView().then { (view) in
            view.backgroundColor = UIColor.lsf_color16(0xcccccc)
            
            contentView.addSubview(view)
            view.snp.makeConstraints({ (maker) in
                maker.leading.trailing.equalToSuperview()
                maker.height.equalTo(0.5)
                maker.top.equalTo(rechargeBtn.snp.bottom).offset(10)
            })
        }
        
        //竖线
        let lineView2 = UIView().then { (view) in
            view.backgroundColor = UIColor.lsf_color16(0xcccccc)
            
            contentView.addSubview(view)
            view.snp.makeConstraints({ (maker) in
                maker.centerX.equalToSuperview()
                maker.width.equalTo(0.5)
                maker.top.equalTo(lineView.snp.bottom)
                maker.bottom.equalToSuperview()
            })
        }
        
        let cancelBtn = UIButton.init(type: .custom).then { (btn) in
            btn.setTitleColor(Config.default.themeColor, for: .normal)
            btn.setTitle("取消", for: .normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
            
            contentView.addSubview(btn)
            btn.snp.makeConstraints({ (maker) in
                maker.leading.bottom.equalToSuperview()
                maker.top.equalTo(lineView.snp.bottom)
                maker.trailing.equalTo(lineView2.snp.leading)
                maker.bottom.equalToSuperview()
            })
        }
        
        
        let enterBtn = UIButton.init(type: .custom).then { (btn) in
            btn.setTitleColor(Config.default.themeColor, for: .normal)
            btn.setTitle("确认", for: .normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
            
            contentView.addSubview(btn)
            btn.snp.makeConstraints({ (maker) in
                maker.trailing.bottom.equalToSuperview()
                maker.top.equalTo(lineView.snp.bottom)
                maker.leading.equalTo(lineView2.snp.trailing)
                maker.size.equalTo(cancelBtn.snp.size)
                maker.bottom.equalToSuperview()
                maker.height.equalTo(44)
            })
        }
        
        cancelBtn.addTarget(self, action: #selector(RechargeAlert.cancelClick), for: .touchUpInside)
        enterBtn.addTarget(self, action: #selector(RechargeAlert.enterClick), for: .touchUpInside)
        rechargeBtn.addTarget(self, action: #selector(RechargeAlert.rechargeClick), for: .touchUpInside)
    }
    
    @objc private func cancelClick() {
        self.hideView(false)
    }
    
    @objc private func enterClick() {
        buy()
    }
    
    //购买
    func buy() {
        startAnimating()
        paperProvider.rx.request(.buy(paperId: paperId)).asObservable().mapRespnseJson().subscribe(onNext: { (response) in
            guard let json = response as? [String: Any] else { return }
            guard let coin = json["goldCoin"] as? Int else { return }
            
            ///保存到本地
            AccountStorage.default.account.goldCoin = coin
            AccountStorage.default.updateAccount()
            
        }, onError: { [weak self] (error) in
            stopAnimating()
            showError(error)
            self?.cancelClick()
        }, onCompleted: { [weak self] in
            stopAnimating()
            
            self?.hideView(true)
            //购买成功
        }).disposed(by: disposeBag)
    }
    
    
    ///充值
    @objc private func rechargeClick() {
        
        let coinVC = CoinViewController.controller()
        coinVC.complete = { [weak self] in
            ///重新显示UI
            self?.getAccountInfo()
        }
        presentController?.navigationController?.pushViewController(coinVC, animated: true)
        
        self.hideView(destroy: false)
    }

}


